//
//  Student.swift
//  SQLite
//
//  Created by 武莎莎 on 15/9/17.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class Student: NSObject {

    var name:String?
    var sex:String?
    var score:Double = 0.0
    var number:Int = 0
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    // 从数据库中取出部分数据，进行字典转模型
    // 返回一个Student的模型数组
    class func students() ->[Student]? {
        let sql = "SELECT number,name,sex,score FROM W_Student LIMIT 20"
        guard let array = SQLiteManager.sharedManager.execRecordSet(sql) else {
            return nil
        }
        
        var student = [Student]()
        // 字典转模型
        for dict in array {
            student.append(Student(dict: dict))
        }
        return student
    }
    
    func insertStudent() ->Bool {
        // 断言：仅在调试的时候有效
        assert(name != nil, "那么属性不能为空！")
        let ssex = sex ?? ""
        // 在文本上一定要加上‘’单引号 :'\(sname)'
        let sql = "INSERT INTO W_Student (name,sex,score) VALUES ('\(name!)','\(ssex)',\(score));"
        number = SQLiteManager.sharedManager.execInsert(sql)
        return number > 0
    }
    
    func updateStudent() ->Bool {
        assert(name != nil, "name不能为空")
        
        let ssex = sex ?? ""
        let sql = "UPDATE W_Student SET \n" + "name = '\(name!)',sex = '\(ssex)',score = \(score) \n" + "WHERE number = \(number)"
        print(sql)
        return SQLiteManager.sharedManager.execSQL(sql)
    }
    
    func deleteStudent() ->Bool {
        let sql = "DELETE FROM W_Student\n" + "WHERE number = \(number)"
        return SQLiteManager.sharedManager.execSQL(sql)
    }
    
    override var description:String {
        let keys = ["name","sex","score","number"]
        return dictionaryWithValuesForKeys(keys).description
    }
}
